package org.dromara.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.platform.domain.TEnterpriseInfo;
import org.dromara.platform.domain.bo.TEnterpriseInfoBo;
import org.dromara.platform.domain.bo.TMiniProgramBaseInfoBo;
import org.dromara.platform.domain.vo.TEnterpriseInfoVo;
import org.dromara.platform.domain.vo.TMiniProgramBaseInfoVo;
import org.dromara.platform.mapper.TEnterpriseInfoMapper;
import org.dromara.platform.service.ITEnterpriseInfoService;
import org.dromara.platform.service.ITMiniProgramBaseInfoService;
import org.dromara.wechat.service.WechatOpenService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import static org.dromara.common.core.constant.Constants.SUCCESS;

/**
 * 企业信息Service业务层处理
 *
 * @author Lion Li
 * @date 2025-05-29
 */
@RequiredArgsConstructor
@Service
public class TEnterpriseInfoServiceImpl implements ITEnterpriseInfoService {

    private final TEnterpriseInfoMapper baseMapper;

    private final ITMiniProgramBaseInfoService miniProgramBaseInfoService;
    private final WechatOpenService wechatOpenService;
    /**
     * 查询企业信息
     *
     * @param id 主键
     * @return 企业信息
     */
    @Override
    public TEnterpriseInfoVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询企业信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 企业信息分页列表
     */
    @Override
    public TableDataInfo<TEnterpriseInfoVo> queryPageList(TEnterpriseInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TEnterpriseInfo> lqw = buildQueryWrapper(bo);
        Page<TEnterpriseInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(vo -> {
            // 查询小程序数量
            vo.setMiniProgram(miniProgramBaseInfoService.getCountByEnterpriseId(vo.getId(), 0));
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的企业信息列表
     *
     * @param bo 查询条件
     * @return 企业信息列表
     */
    @Override
    public List<TEnterpriseInfoVo> queryList(TEnterpriseInfoBo bo) {
        LambdaQueryWrapper<TEnterpriseInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TEnterpriseInfo> buildQueryWrapper(TEnterpriseInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TEnterpriseInfo> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TEnterpriseInfo::getId);
        lqw.like(StringUtils.isNotBlank(bo.getName()), TEnterpriseInfo::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), TEnterpriseInfo::getCode, bo.getCode());
        lqw.eq(bo.getCodeType() != null, TEnterpriseInfo::getCodeType, bo.getCodeType());
        lqw.eq(bo.getAuthorize() != null, TEnterpriseInfo::getAuthorize, bo.getAuthorize());
        lqw.eq(StringUtils.isNotBlank(bo.getLegalPersonaWechat()), TEnterpriseInfo::getLegalPersonaWechat, bo.getLegalPersonaWechat());
        lqw.like(StringUtils.isNotBlank(bo.getLegalPersonaName()), TEnterpriseInfo::getLegalPersonaName, bo.getLegalPersonaName());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), TEnterpriseInfo::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getLogo()), TEnterpriseInfo::getLogo, bo.getLogo());
        lqw.eq(StringUtils.isNotBlank(bo.getCertificateOfBusiness()), TEnterpriseInfo::getCertificateOfBusiness, bo.getCertificateOfBusiness());
        return lqw;
    }

    /**
     * 新增企业信息
     *
     * @param bo 企业信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TEnterpriseInfoBo bo) {
        try {
            validEntityBeforeSave(bo);
            TEnterpriseInfo add = MapstructUtils.convert(bo, TEnterpriseInfo.class);
            boolean flag = baseMapper.insert(add) > 0;
            if (flag) {
                bo.setId(add.getId());
            }
            return flag;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 修改企业信息
     *
     * @param bo 企业信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TEnterpriseInfoBo bo) {
        try {
            validEntityBeforeSave(bo);
            TEnterpriseInfo update = MapstructUtils.convert(bo, TEnterpriseInfo.class);
            return baseMapper.updateById(update) > 0;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TEnterpriseInfoBo bo){
        //TODO 做一些数据校验,如唯一约束
        if(!checkEnterpriseInfoUnique(bo)){
            throw new IllegalArgumentException("存在相同的企业代码、企业名称、法人微信号、法人姓名已存在");
        }
    }

    /**
     * 校验并批量删除企业信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public boolean checkEnterpriseInfoUnique(TEnterpriseInfoBo bo) {
        TEnterpriseInfoVo tEnterpriseInfoVo = getUnique(bo);
        if(null != tEnterpriseInfoVo){
            if(!tEnterpriseInfoVo.getId().equals(bo.getId())){
                return false;
            }
        }
        return true;
    }

    public TEnterpriseInfoVo getUnique(TEnterpriseInfoBo bo) {
        LambdaQueryWrapper<TEnterpriseInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(TEnterpriseInfo::getName, bo.getName());
        lqw.eq(TEnterpriseInfo::getCode, bo.getCode());
        lqw.eq(TEnterpriseInfo::getLegalPersonaWechat, bo.getLegalPersonaWechat());
        lqw.eq(TEnterpriseInfo::getLegalPersonaName, bo.getLegalPersonaName());
        return baseMapper.selectVoOne(lqw);
    }

    @Override
    public void updateMiniProgramResultAndAppId(TEnterpriseInfoBo bo, String appId, Integer status) {
        TEnterpriseInfoVo tEnterpriseInfoVo = getUnique(bo);
        if (null != tEnterpriseInfoVo) {
            // 查询小程序是否存在，不存在则新增
            // 存在，更新状态
            TMiniProgramBaseInfoBo miniProgramBaseInfoBo = new TMiniProgramBaseInfoBo();
            miniProgramBaseInfoBo.setEnterpriseId(tEnterpriseInfoVo.getId());
            miniProgramBaseInfoBo.setAppid(appId);
            List<TMiniProgramBaseInfoVo> tMiniProgramBaseInfoVoList = miniProgramBaseInfoService.queryList(miniProgramBaseInfoBo);
            if (tMiniProgramBaseInfoVoList.size() == 0) {
                miniProgramBaseInfoService.insertByBo(miniProgramBaseInfoBo);
            } else {
                TMiniProgramBaseInfoVo tMiniProgramBaseInfoVo = tMiniProgramBaseInfoVoList.get(0);
                TMiniProgramBaseInfoBo updateBo = new TMiniProgramBaseInfoBo();
                updateBo.setId(tMiniProgramBaseInfoVo.getId());
                updateBo.setStatus(status);
                updateBo.setRemark("微信推送注册结果");
                miniProgramBaseInfoService.updateByBo(updateBo,null);
            }
        }
    }

    @Override
    public R register(TEnterpriseInfoBo enterpriseInfoBo) {
        try {
            String result = wechatOpenService.registerMiniprogram(enterpriseInfoBo.getName(), enterpriseInfoBo.getCode(), enterpriseInfoBo.getCodeType(), enterpriseInfoBo.getLegalPersonaWechat(), enterpriseInfoBo.getLegalPersonaName(), enterpriseInfoBo.getPhone());
            // 注册小程序申请成功，更新企业小程序状态
            if (SUCCESS.equals(result)) {
                updateMiniProgramResultAndAppId(enterpriseInfoBo, result, 1);
            } else {
                return R.fail(result);
            }
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok(SUCCESS);
    }
}
